package com.example.rxjava0305;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button button;
    private Button btn2;
    private static final String PATH="https://s3.bmp.ovh/imgs/2022/03/b39ed30822997416.jpg";
    private Handler mHandler;
    private ProgressDialog progressDialog;
    private final String TAG =MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        Reception();
        btnRXClock();
        btn2Click();
    }

    /**
     * 控件初始化
     */
    private void initView() {
        imageView=findViewById(R.id.image_picture);
        button=findViewById(R.id.btn_get_picture);
        btn2 = findViewById(R.id.btn_picture);
    }
    /**
     * 点击按钮从网络请求图片(RxJava写法)
     * *******RxJava代码执行流程
     * 1.订阅（开始观察）并开始执行观察者中的onSubscribe方法
     * 2.分发事件，数据源开始向下执行
     * 3.数据从String类型成功转为Bitmap类型之后开始执行观察者中的onNext方法
     * 4.当数据没有从String类型转为Bitmap类型则走观察者中的onError方法
     * 5.事件结束，走观察者中的onComplete方法
     */
    private void btnRXClock(){
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //事件源
                Observable.just(PATH)//被观察者
                //将数据源从String类型，变为Bitmap类型
                .map(new Function<String, Bitmap>() {//处理耗时操作
                    @Override
                    public Bitmap apply(String s) throws Throwable {
                        URL url=new URL(PATH);
                        URLConnection urlConnection=url.openConnection();
                        HttpURLConnection httpURLConnection= (HttpURLConnection) urlConnection;
                        httpURLConnection.setConnectTimeout(5000);
                        int responseCode = httpURLConnection.getResponseCode();//服务器交互码
                        if (HttpURLConnection.HTTP_OK==responseCode) {
                            Bitmap bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
                            return bitmap;
                        }
                        return null;
                    }
                })
                //给被观察者分配异步线程
                .subscribeOn(Schedulers.io())
                //给观察者分配线程，切回主线程
                .observeOn(AndroidSchedulers.mainThread())
                //订阅（通过订阅将被观察者跟观察者联系起来）
               .subscribe(
                       new Observer<Bitmap>() {
                           @Override
                   public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                       //创建一个下载提示框
                       progressDialog = new ProgressDialog(MainActivity.this);
                       progressDialog.setTitle("下载中");//提示框标题
                       progressDialog.show();
                   }

                   @Override
                   public void onNext(@io.reactivex.rxjava3.annotations.NonNull Bitmap bitmap) {
                       Log.d(TAG,"数据转换成功");
                       //更新UI
                       imageView.setImageBitmap(bitmap);
                   }

                   @Override
                   public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                       Log.d(TAG,"数据转换成功");

                   }

                   @Override
                   public void onComplete() {
                       //最终点，执行到这儿表示整个RxJava这个链条执行完毕
                       //关闭加载框
                       if (progressDialog!=null)progressDialog.dismiss();

                   }
               });
            }
        });
    }

    /**
     * 普通多线程方式写法
     */
    private void btn2Click(){
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建一个下载提示框
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("下载中");//提示框标题
                progressDialog.show();
                new Thread(new Runnable() {//使用另一个线程来进行耗时操作
                    @Override
                    public void run() {
                        try {
                            URL url=new URL(PATH);
                            URLConnection urlConnection=url.openConnection();
                            HttpURLConnection httpURLConnection= (HttpURLConnection) urlConnection;
                            //httpURLConnection.setRequestMethod("GET");//默认为get请求
                            httpURLConnection.setConnectTimeout(5000);
                            int responseCode = httpURLConnection.getResponseCode();//服务器交互码
                            Log.d(TAG,"交互码"+responseCode);
                            if (HttpURLConnection.HTTP_OK==responseCode){
                                Bitmap bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
                                Message message = mHandler.obtainMessage();
                                message.obj=bitmap;
                                mHandler.sendMessage(message);
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();//启动线程
            }
        });
    }

    /**
     * 主线程接收子线程传入的网络下载成功的图片，并进行ui改变
     */
    private void Reception() {
        mHandler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Bitmap bitmap= (Bitmap) msg.obj;
                imageView.setImageBitmap(bitmap);
                if (progressDialog!=null){
                    progressDialog.dismiss();
                }

            }
        };
    }

}